<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <input type="file"/>
    <div class="box">
      <% list.forEach(img=>{ %>
        <img style="width:100px;height:100px;"  src="/ajaxdemo/img/"+<%= img.filename%>/>

      <% }) %>

    </div>

    <script type="text/javascript">
      const fileDOM = document.querySelector("input[type='file']");
      // console.log(fileDOM);

      fileDOM.addEventListener("change", function(event){
        var formData = new FormData();
        formData.append("imgfile", event.target.files[0]);
        // console.log(formData);
        upload(formData);

        function upload(formdata){
          var xhr = new XMLHttpRequest();
          xhr.open("POST", "/ajaxdemo/up");
          xhr.responseType = "json";
          xhr.onreadystatechange = function(){
            if (xhr.status == 200 && xhr.readyState == 4) {
              console.log(xhr.response);
              const imgurl = "/ajaxdemo/img/"+xhr.response.filename;
              addImage(imgurl);
            }
          }

          xhr.send(formdata);
        }

        function addImage(url){
          const img = new Image();
          img.src = url;
          img.width = "100";
          img.height = "100";
          const boxDOM = document.querySelector(".box");
          boxDOM.appendChild(img);
        }
      });
    </script>

  </body>
</html>
